package com.x.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

public class FileUtil {

	private static Logger log = Logger.getLogger(FileUtil.class);

	public static boolean uploadFile(InputStream is, String filePath) {
		boolean retCode = false;
		byte[] buffer = new byte[1024];
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(filePath));
			int n = -1;
			while ((n = is.read(buffer, 0, buffer.length)) != -1) {
				fos.write(buffer, 0, n);
			}
			retCode = true;
			log.info("upload file success...");
		} catch (FileNotFoundException fnfe) {
			log.error("fnfe:" + fnfe);
		} catch (IOException ioe) {
			log.error("ioe:" + ioe);
		} finally {
			if (fos != null) {
				try {
					fos.close();
					fos = null;
				} catch (IOException e) {
					log.error(e);
				}
			}
			if (is != null) {
				try {
					is.close();
					is = null;
				} catch (IOException e) {
					log.error(e);
				}

			}
		}
		return retCode;
	}

	/**
	 * 将文件信息转换为MAP存储
	 * 
	 * @param fileName
	 * @return
	 */
	public static Map<String, String> getFileContentToMap(String fileName) {
		Map<String, String> map = new LinkedHashMap<String, String>();
		BufferedReader reader = null;
		FileInputStream f = null;
		String[] lines = null;
		try {
			f = new FileInputStream(fileName);
			reader = new BufferedReader(new InputStreamReader(f, "UTF-8"));
			String line = "";
			while ((line = reader.readLine()) != null) {
				if (line.startsWith("#")) {
					continue;
				}
				lines = line.split("`");
				if (lines.length >= 2) {
					map.put(lines[0], lines[1]);
				}
			}
		} catch (Exception e) {
			log.error(e);
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
				if (f != null) {
					f.close();
				}
			} catch (IOException e) {
				log.error(e);
			} finally {
				reader = null;
				f = null;
			}
		}
		return map;
	}

	public static String getFileContent(String fileName) {
		BufferedReader reader = null;
		StringBuilder fileContent = new StringBuilder();
		try {
			File f = new File(fileName);
			reader = new BufferedReader(new FileReader(f));
			String line = "";
			while ((line = reader.readLine()) != null) {
				fileContent.append(line);
				fileContent.append("\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				log.error(e);
			} finally {
				reader = null;
			}
		}
		return fileContent.toString();
	}

	public static String getFileContent(InputStream is) {
		BufferedReader reader = null;
		StringBuilder fileContent = new StringBuilder();
		try {
			reader = new BufferedReader(new InputStreamReader(is));
			String line = "";
			while ((line = reader.readLine()) != null) {
				fileContent.append(line);
				fileContent.append("\n");
			}
		} catch (Exception e) {
			log.error(e);
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				log.error(e);
			} finally {
				reader = null;
			}
		}
		return fileContent.toString();
	}

	/**
	 * 设置文本内容
	 * 
	 * @param path
	 * @param content
	 * @return
	 */
	public static boolean setFileContent(String path, String content) {
		boolean flag = false;
		FileOutputStream fos = null;
		Writer out = null;
		try {
			fos = new FileOutputStream(path);
			out = new OutputStreamWriter(fos, "UTF-8");
			out.write(content);
			out.flush();
			flag = true;
		} catch (Exception e) {
			log.error(e);
		} finally {
			try {
				if (out != null)
					out.close();
				if (fos != null)
					fos.close();
			} catch (Exception e) {
				log.error(e);
			} finally {
				out = null;
				fos = null;
			}
		}
		return flag;
	}

	/**
	 * public static String file2Base64String(String filePath, String tmpDir) {
	 * File file = new File(filePath);
	 * 
	 * String tmpFilePath = tmpDir + "/" + UUID.randomUUID().toString() +
	 * ".base64"; File tmpFile = new File(tmpFilePath);
	 * 
	 * StringBuffer sb = new StringBuffer(); BufferedReader br = null; try {
	 * Base64.encode(file, tmpFile);
	 * 
	 * // Read All Base 64 File br = new BufferedReader(new
	 * FileReader(tmpFile)); String tmpStr = null; while ((tmpStr =
	 * br.readLine()) != null) { sb.append(tmpStr); } } catch
	 * (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e)
	 * { e.printStackTrace(); } finally { try { if (br != null) { br.close(); br
	 * = null; } } catch (IOException e) { e.printStackTrace(); } }
	 * 
	 * tmpFile.delete(); return sb.toString();
	 * 
	 * }
	 **/

	/**
	 * 获取文件名
	 */
	public static String getFileExt(String fileName) {
		if (fileName == null)
			return "";

		String ext = "";
		int lastIndex = fileName.lastIndexOf(".");
		if (lastIndex >= 0) {
			ext = fileName.substring(lastIndex + 1).toLowerCase();
		}
		return ext;
	}

	/**
	 * 获取文件MD5值
	 * 
	 * @param path
	 * @return
	 * @throws FileNotFoundException
	 */
	public static String getMd5ByFile(String path) throws Exception {
		// String value = null;
		// FileInputStream in = null;
		// try {
		// in = new FileInputStream(file);
		// MappedByteBuffer byteBuffer =
		// in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
		// MessageDigest md5 = MessageDigest.getInstance("MD5");
		// md5.update(byteBuffer);
		// BigInteger bi = new BigInteger(1, md5.digest());
		// value = bi.toString(16);
		// } catch (Exception e) {
		// log.error(e);
		// } finally {
		// if (null != in) {
		// try {
		// in.close();
		// } catch (IOException e) {
		// log.error(e);
		// }
		// }
		// in = null;
		// }
		// return value;
		//
		FileInputStream fis = new FileInputStream(path);
		String md5 = DigestUtils.md5Hex(IOUtils.toByteArray(fis));
		IOUtils.closeQuietly(fis);
		return md5;
	}

	/**
	 * 获取文件格式
	 */
	public static String getFileType(String fileName) {
		if (fileName == null)
			return "";

		String type = "";
		int lastIndex = fileName.lastIndexOf(".");
		if (lastIndex >= 0) {
			type = fileName.substring(lastIndex + 1, fileName.length()).toLowerCase();
		}

		return type;
	}

	public static void main(String[] args) {
		System.out.println(getFileType("abc.txt"));
	}
}
